package com.dss.sdk.utils.json;

import com.google.gson.JsonParseException;
import com.google.gson.ToNumberStrategy;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.MalformedJsonException;

import java.io.IOException;

/**
 * 自定义Gson数字转换策略；
 * 优先转换为Integer，如果转换失败再转换为Long，如果再次转换失败再转换为Double
 */
public class IntOrLongOrDoubleStrategy implements ToNumberStrategy {

    @Override
    public Number readNumber(JsonReader in) throws IOException {
        String value = in.nextString();
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException intE) {
            try {
                return Long.parseLong(value);
            } catch (NumberFormatException longE) {
                try {
                    Double d = Double.valueOf(value);
                    if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) {
                        throw new MalformedJsonException("JSON forbids NaN and infinities: " + d + "; at path " + in.getPreviousPath());
                    }
                    return d;
                } catch (NumberFormatException doubleE) {
                    throw new JsonParseException("Cannot parse " + value + "; at path " + in.getPreviousPath(), doubleE);
                }
            }
        }
    }
}
